//
//  DaogAndJianzViewController.m
//  JiuKuGospel
//
//  Created by jiukuyinyue on 16/8/1.
//  Copyright (c) 2016年 JiuKuForApp. All rights reserved.
//

#import "DaogAndJianzViewController.h"
#import "ChannelModel.h"
#import "ChannelLabel.h"
//#import "VideoCollectionViewCell.h"

@interface DaogAndJianzViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, strong) NSMutableArray *labelsM;


@property (nonatomic, strong)UITableView * typeTab;

@property (nonatomic, strong)NSArray * typeArr;


@end

@implementation DaogAndJianzViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"祷告见证";
    [self createChannelLabels];//不能放在viewWillAppear

    _channelScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth, 44)];
    _channelScrollView.delegate = self;
    _channelScrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_channelScrollView];

    [LSZSpecialPackaging addThreadWithOtherRGB:_channelScrollView A:0 B:_channelScrollView.frame.size.height-1 C:_channelScrollView.frame.size.width D:1 R:210 G:210 BB:210];
    self.newsCollectionViewFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.newsCollectionViewFlowLayout.itemSize = CGSizeMake(ScreenWidth, ScreenHeight-CGRectGetMaxY(_channelScrollView.frame));
    self.newsCollectionViewFlowLayout.minimumInteritemSpacing = 0;
    self.newsCollectionViewFlowLayout.minimumLineSpacing = 0;

    _newsCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(_channelScrollView.frame), ScreenWidth, ScreenHeight-CGRectGetMaxY(_channelScrollView.frame)) collectionViewLayout: self.newsCollectionViewFlowLayout];
    _newsCollectionView.delegate = self;
    _newsCollectionView.dataSource = self;
    _newsCollectionView.scrollsToTop = NO;
    _newsCollectionView.showsVerticalScrollIndicator = NO;
    _newsCollectionView.showsHorizontalScrollIndicator = NO;
    // 设置分页效果
    self.newsCollectionView.pagingEnabled = YES;
    // 禁用弹簧效果
    self.newsCollectionView.bounces = NO;
    // 设置滚动方向
    self.newsCollectionViewFlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 设置最小间距
    self.newsCollectionViewFlowLayout.minimumLineSpacing = 0;
    self.newsCollectionViewFlowLayout.minimumInteritemSpacing = 0;
    _newsCollectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_newsCollectionView];

    [self.newsCollectionView registerClass:[LSZDaoGCollectionViewCell class] forCellWithReuseIdentifier:@"LSZDaoGCollectionViewCell"];
    // 实例化频道标签缓存池
    _labelsM = [NSMutableArray array];
    self.automaticallyAdjustsScrollViewInsets = NO;

    self.channelScrollView.showsVerticalScrollIndicator = FALSE;
    self.channelScrollView.showsHorizontalScrollIndicator = FALSE;
    [self addButRight];
    /**增加侧滑返回,无其他作用*/
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, ScreenHeight)];
    [self.view addSubview:view];
    [self.view bringSubviewToFront:view];
}
-(void)addButRight
{
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 40, 40);
    [rightBtn setTitle:@"发布" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    if (ScreenWidth == 320) {
        //5
        rightBtn.titleLabel.font = FONT_15;
    }else if(ScreenWidth == 375){
        // 6 7
        rightBtn.titleLabel.font = FONT_(15.5);
    }else {
        //plus
        rightBtn.titleLabel.font = FONT_16;
    }
    [rightBtn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
}
/// 能够执行到这个方法,NewsCollectionView大小一定是正确的
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // 把cell的大小设置成跟NewsCollectionView一般大
    self.newsCollectionViewFlowLayout.itemSize = self.newsCollectionView.bounds.size;
}
/// 创建频道标签控件 : 根据频道标签模型数组的元素个数而定的
- (void)createChannelLabels {
#pragma mark - 上面选择标题的请求  这个是写在代码里面的死值和id,后台让这样办的
    __weak typeof(self) weakSelf = self;
    [ChannelModel getNewsCateWithSuccBlock:^(NSArray *modelArr) {
        if (modelArr != nil){
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                weakSelf.channelModels = modelArr;
                [weakSelf.newsCollectionView reloadData];//刷新UI
                // 定义宽高
                CGFloat labelH = 44; // 也可以指定为父视图的高度
                // 遍历频道标签模型数组
                for (NSInteger i = 0; i < self.channelModels.count; i++) {
                    // 创建频道标签
                    ChannelLabel *label = [ChannelLabel new];
                    // 添加到父视图
                    [weakSelf.channelScrollView addSubview:label];
                    // 赋值
                    ChannelModel *model = weakSelf.channelModels[i];
                    label.text = model.title;
                    label.textColor =  RGBColor(51, 51, 51);
                    // 创建点击手势
                    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(channelLabelTapClick:)];
                    // 添加到label
                    [label addGestureRecognizer:tap];
                    float titleFont = [LSZSpecialPackaging initWithReturnsthesizeOf:15 :0.5];
                    label.font = FONT_(titleFont);
                    // 开启交互
                    label.userInteractionEnabled = YES;
                    // 设置tag : 方便在点击时知道当前点击的是第几个
                    label.tag = i+1;
                    // 把每次创建的label,按顺序添加到容器
                    [self.labelsM addObject:label];
                    //                    CGFloat widthText = [LSZSpecialPackaging caculateWidthOfText:ScreenWidth height:44 font:titleFont :model.title];
                    // 把第0个label默认缩放到最大
                    if (i == 0) {
                        label.scale = 1.0;
                        label.frame = CGRectMake(0, 0, ScreenWidth/3, labelH);
                        //去掉精品等  先暂时均分3个
                    }else{
                        UILabel * labelLastOne = [self.view viewWithTag:i];
                        //去掉精品等  先暂时均分3个
                        label.frame = CGRectMake(CGRectGetMaxX(labelLastOne.frame), 0, ScreenWidth/3, labelH);
                        if (i ==  self.channelModels.count-1) {
                            self.channelScrollView.contentSize = CGSizeMake(CGRectGetMaxX(label.frame), 0);
                            [LSZSpecialPackaging addThreadWithOtherRGB:self.channelScrollView A:0 B:self.channelScrollView.frame.size.height-1 C:CGRectGetMaxX(label.frame) D:1 R:241 G:241 BB:241];
                        }
                    }
                }
                if(weakSelf.channelModels.count == 0){
                    //判断是否有无数据
                    UIImageView *imageView = [[UIImageView alloc] init];
                    imageView.image = [UIImage imageNamed:@"头条背景"];
                    weakSelf.view = imageView;
                    return;
                }
            }];
        }
    }];
}
/// 频道标签手势点击事件
- (void)channelLabelTapClick:(UITapGestureRecognizer *)tap {
    // 1.把选中的频道标签居中
    // 1.1 需要找到点击的是哪个标签
    ChannelLabel *tapLabel = (ChannelLabel *)tap.view;
    // 1.2 计算选中的标签居中时,需要滚动的距离
    CGFloat offsetX = tapLabel.center.x - self.view.bounds.size.width*0.5;
    // 1.3 限制最大和最小滚动范围
    CGFloat minOffset = 0;
    CGFloat maxOffset = self.channelScrollView.contentSize.width - self.view.bounds.size.width;
    if (offsetX < minOffset) {
        offsetX = minOffset;
    }
    if (offsetX > maxOffset) {
        offsetX = maxOffset;
    }
    // 1.4 获取需要滚动到的点
    CGPoint point = CGPointMake(offsetX, 0);
    // 1.5 频道滚动视图滚动到标签居中的位置
    [self.channelScrollView setContentOffset:point animated:YES];
    // 2.新闻视图滚动到对应的item
    // 2.1 获取需要滚动到的item的角标
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:tapLabel.tag-1 inSection:0];
    // 2.2 滚动到指定的item
    [self.newsCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    // 遍历所有的label,如果是点击的那个就设置最大缩放比,如果不是点击的那个就把缩放比设置为最小
    for (NSInteger i = 0; i < _labelsM.count; i++) {
        // 取出所有的label
        ChannelLabel *label = _labelsM[i];
        // 判断取出的label是否是选中的label,如果是就设置最大缩放比
        if (i == tapLabel.tag-1) {
            label.scale = 1.0;
        } else {
            label.scale = 0.0;
        }
    }
}
/// 当新闻滚动视图滚动结束后,频道标签居中
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView != self.channelScrollView) {
        // 计算当前滚动到第几个角标
        NSInteger index = scrollView.contentOffset.x / self.view.bounds.size.width;
        // 获取滚动新闻视图时,对应的标签
        ChannelLabel *label = _labelsM[index];
        // 计算当滚动新闻视图时,对应的标签居中时需要滚动的距离
        CGFloat offsetX = label.center.x - self.view.bounds.size.width*0.5;
        // 限制最大和最小 滚动范围
        CGFloat minOffset = 0;
        CGFloat maxOffset = self.channelScrollView.contentSize.width - self.view.bounds.size.width;
        if (offsetX < minOffset) {
            offsetX = minOffset;
        }
        if (offsetX > maxOffset) {
            offsetX = maxOffset;
        }
        // 获取居中时需要滚动到的点
        CGPoint point = CGPointMake(offsetX, 0);
        // 滚动新闻视图时,把对应的标签居中
        [self.channelScrollView setContentOffset:point animated:YES];
    }
}
/// 监听实时滚动,实时缩放
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView != self.channelScrollView) {
        // 获取当前滚动到的整数角标
        NSInteger index = scrollView.contentOffset.x / self.view.bounds.size.width;
        for (int i = 0; i<_labelsM.count; i++) {
            ChannelLabel *leftLabel = _labelsM[i];
            if (i == index) {
                leftLabel.scale = 1;
            }else{
                leftLabel.scale = 0;
            }
        }
    }
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    // 频道标签有多少个就一一对应多少个cell
    return  self.channelModels.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LSZDaoGCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LSZDaoGCollectionViewCell" forIndexPath:indexPath];
    [self addChildViewController:cell.videoVC];
    // 获取NewsCollectionViewCell对应的频道标签对应的模型
    ChannelModel * model = nil;
    model = self.channelModels[indexPath.item];
    // 拼接新闻URL
    NSString *cid = [NSString stringWithFormat:@"%@",model.id];
    // 把拼接好的新闻地址传给cell
    cell.cid = cid;//ID
    return cell;
}
#pragma mark - 发布
-(void)rightBtnAction
{
    if([[_UserM usercode] isEqualToString:@""]){
        [self gotoLogin];
    }else{
        LSZReleasePrayerAndWitnessVC * vc = [[LSZReleasePrayerAndWitnessVC alloc]init];
        vc.choosePosted = 1;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

@end
